package com.synv.flashcard;

import java.io.File;
import java.io.IOException;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.synv.entity.Category;
import com.synv.flashcard.R.color;
import com.synv.util.CategoryAdapter;
import com.synv.util.DataBaseHelper;
import com.synv.util.WebParserUtils;

public class MainActivity extends Activity {

	private ListView listView;
	private EditText txtNewCategory;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		
		ActionBar actionBar = getActionBar();
		actionBar.setBackgroundDrawable(new ColorDrawable(color.header));
		actionBar.setTitle("English Flash Card");
		
		LinearLayout contentView = (LinearLayout) findViewById(R.id.containView);
		txtNewCategory = (EditText) findViewById(R.id.txtNewCategory);
		listView = (ListView)findViewById(R.id.list_card);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent contentScreen = new Intent(getApplicationContext(), ContentActivity.class);
				Category category = (Category)parent.getItemAtPosition(position);
				contentScreen.putExtra("categorySeq", category.getSeq());
				contentScreen.putExtra("categoryName", category.getName());
				startActivity(contentScreen);
			}
        });
		
		Button btnSaveNewCategory = (Button) findViewById(R.id.btnSaveNewCategory);
		btnSaveNewCategory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				addNewCategory();
				txtNewCategory.setText("");
			}
		});
		
		init();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		init();
	};

	private void init() {
		File folder = new File(WebParserUtils.DEFAULT_FOLDER);
		folder.mkdirs();
		DataBaseHelper myDbHelper = new DataBaseHelper(this);
		try {
			myDbHelper.createDataBase();
		} catch (IOException e) {
			Log.d("Copy database ERROR", e.getMessage());
		}
		
		myDbHelper.close();
		Cursor c = myDbHelper.getReadableDatabase().query("category", null, null, null, null, null, "seq");
		Category category_data[] = new Category[c.getCount()];
		c.moveToFirst();
		int i = 0;
		while(!c.isAfterLast()) {
			Integer seq = c.getInt(0);
			String name = c.getString(1);
			Integer bookmark = c.getInt(2);
			boolean isNew = c.getInt(3) > 0 ? true : false;
			Category category = new Category(seq, name, bookmark, isNew);
			category_data[i] = category;
			i++;
			c.moveToNext();
		}
		
		CategoryAdapter adapter = new CategoryAdapter(this, R.layout.category_item_row, category_data);
		listView.setAdapter(adapter);
		listView.requestFocus();
		InputMethodManager imm = (InputMethodManager)getSystemService(
			      Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(txtNewCategory.getWindowToken(), 0);
	}
	
	private void addNewCategory() {
		String categoryName = txtNewCategory.getText().toString().trim();
		if("".equals(categoryName)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Bạn phải nhập tên danh sách!")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                //do things
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
			return;
		}
		for(int i = 0; i < listView.getAdapter().getCount(); i++) {
			Category category = (Category)listView.getAdapter().getItem(i);
			if(categoryName.trim().equals(category.getName())) return;
		}
		DataBaseHelper myDbHelper = new DataBaseHelper(this);
		myDbHelper.getWritableDatabase().execSQL("INSERT INTO Category (Name, IsNew) VALUES ('" + categoryName.replaceAll("'", "''") + "', 1)");
		Cursor c = myDbHelper.getReadableDatabase().query("category", null, "Name='" + categoryName.replaceAll("'", "''") + "'", null, null, null, "seq");
		c.moveToFirst();
		Integer seq = c.getInt(0);
		String name = c.getString(1);
		Integer bookmark = c.getInt(2);
		boolean isNew = c.getInt(3) > 0 ? true : false;
		Category category = new Category(seq, name, bookmark, isNew);
		myDbHelper.close();
		
		viewDetail(category);
	}
	
	private void viewDetail(Category category) {
		Intent categoryDetail = new Intent(this, CategoryDetailActivity.class);
		categoryDetail.putExtra("categorySeq", category.getSeq());
		categoryDetail.putExtra("categoryName", category.getName());
		startActivity(categoryDetail);
	}
}
